package com.mall.util;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.InputStream;


/**
 * 文件上传工具类
 */

public class UploadFileUtil {


    //设置好账号的ACCESS_KEY和SECRET_KEY
    //设置好账号的ACCESS_KEY和SECRET_KEY
   final static String accessKey = "CgBOMyII1sDG7YkTkhuyiyeOVf3UqeSi4ndRaqaP"; //这两个登录七牛 账号里面可以找到
    final static String secretKey = "hBh6jXw3bmMhAYkgJmBj4HXu1av4_nEsaOVsQXAU";

    //要上传的空间
  final  static   String bucket = "101library"; //对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置私有）
    //上传到七牛后保存的文件名


    private static String OuterChain = "s79b95neb.hn-bkt.clouddn.com";

    /**
     * 上传文件并且返回文件地址
     *
     * @param inputStream 文件
     */
    public static DefaultPutRet setUploadManager(InputStream inputStream, String fileName) {
        //设置密钥、文件连接、文件名等等属性
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //设置连接地址
        Auth auth = Auth.create(accessKey, secretKey);
        String key  = fileName;
        String prefix = "";
        int Guid = 100;
        try {

            String upToken = auth.uploadToken(bucket);
            //生成文件名
//            String s1 = UUID.randomUUID().toString();
            //实现文件上传
            Response response = uploadManager.put(inputStream, key, upToken, null, null);
            //解析上传成功结果
            DefaultPutRet defaultPutRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println("文件外链地址：" + OuterChain +"/"+ defaultPutRet.key);
            System.out.println("defaultPutRet.hash = " + defaultPutRet.hash);
            return defaultPutRet;
        } catch ( QiniuException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
//
//    public static String  uplaodFile(MultipartFile file,String fileName){
//
//        // 图片存储路径
//        try {
//            InputStream inputStream = file.getInputStream();
//            DefaultPutRet defaultPutRet = setUploadManager(inputStream, fileName);
//                    String filePath = "http://"+OuterChain +"/"+ fileName;
//                    return filePath;
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    return  "";
//
//    }

    public static String  uplaodFile(InputStream is,String fileName){
        // 图片存储路径
        DefaultPutRet defaultPutRet = setUploadManager(is, fileName);
        String filePath = "http://"+OuterChain +"/"+ fileName;
        return filePath;
    }


}
